<?php

namespace app\command;

use app\api\service\UserOrderService;
use support\spark\model\order\Order;
use support\spark\model\user\User;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;


class SparksAutoAppraise extends Command
{
    protected static $defaultName = 'sparks:autoAppraise';
    protected static $defaultDescription = 'SparkShop商城自动评价';


    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $orderModel = new Order();
        $orderNum = $orderModel->where('status', 6)->where('user_comments', 1)->count('id');
        $systemConfig = getConfByType('shop_base');
        $autoAppraiseDay = $systemConfig['auto_goods_appraise'] ?: 3;
        $limit = 1000;
        $page = 1;
        $pageSize = ceil($orderNum / $limit);
        $userModel = new User();
        $userOrderService = new UserOrderService();

        for ($i = 0; $i < $pageSize; $i++) {
            $offset = ($page - 1) * $limit;
            $orderList = $orderModel->select(['id', 'user_id', 'received_time'])->with('detailSimple')->where('status', 6)
                ->where('user_comments', 1)->limit($offset, $limit)->get();
            $orderList = $orderList ? $orderList->toArray() : [];
            foreach ($orderList as $vo) {

                $overTime = date('Y-m-d H:i:s', strtotime($vo['received_time']) + $autoAppraiseDay * 86400);
                if ($overTime < now()) {
                    $userInfo = $userModel->findOne(['id' => $vo['user_id']], 'nickname,avatar')['data'];

                    foreach ($vo['detailSimple'] as $v) {
                        $userOrderService->doAppraise([
                            'content' => '自动评价',
                            'desc_match' => 5,
                            'order_detail_id' => $v['id'],
                            'order_id' => $vo['id'],
                            'pictures' => "",
                            'type' => 1
                        ], [
                            'id' => $vo['user_id'],
                            'name' => $userInfo['nickname'],
                            'avatar' => $userInfo['avatar']
                        ]);
                    }
                }
            }

            $page += 1;
        }
        return self::SUCCESS;
    }

}
